/**
 * 深拷贝
 * @param obj
 * @returns
 */
export function deepClone<T = any>(obj: T): T {
  const result: any = Array.isArray(obj) ? [] : {}
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      if (typeof obj[key] === 'object') {
        result[key] = deepClone(obj[key]) //递归复制
      } else {
        result[key] = obj[key]
      }
    }
  }
  return result
}
/**
 * 获取指定区间的随机整数
 * @param min
 * @param max
 * @returns
 */
export function getRandomInt(min: number, max: number) {
  return Math.floor(Math.random() * (max - min + 1)) + min
}
/**
 *  节流函数
 * @param this
 * @param func
 * @param wait
 * @param options
 * @returns
 */
export function throttle(this: any, func: Function, wait: number, options: any = {}) {
  let context: any = this
  let args: any = arguments
  let timeout: any
  let previous = 0
  const later = function () {
    previous = options.leading === false ? 0 : Date.now()
    timeout = null
    func.apply(context, args)
  }
  const throttled = function (this: any) {
    const now = Date.now()
    if (!previous && options.leading === false) previous = now
    const remaining = wait - (now - previous)
    context = this
    args = arguments
    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout(timeout)
        timeout = null
      }
      previous = now
      func.apply(context, args)
    } else if (!timeout && options.trailing !== false) {
      timeout = setTimeout(later, remaining)
    }
  }
  return throttled
}

/**
 * 防抖函数
 * @param func
 * @param wait
 * @param immediate
 * @returns
 */
export function debounce(func: Function, wait: number, immediate = false) {
  let timeout: any
  return function (this: any, ...args: any[]) {
    if (timeout) clearTimeout(timeout)
    if (immediate) {
      const callNow = !timeout
      timeout = setTimeout(() => {
        timeout = null
      }, wait)

      if (callNow) func.apply(this, args)
    } else {
      timeout = setTimeout(() => {
        func.apply(this, args)
      }, wait)
    }
  }
}
